<script setup lang="ts">
import { onMounted, reactive, ref, watch, computed } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import API from '@/services';
import { useStore } from '@/store';
import DimensionModelGraph from '../../dimensionDetail/components/DimensionModelGraph/ModelGraph';

const store = useStore();
const emit = defineEmits([
  'showBindModal',
  'reviseModal',
  'clearDimension',
  'updateList'
]);
const formRef = ref();
const defaultFormData = {
  tableId: '', // 数据表id
  tableName: '', //数据表名称
  dimensionTableDesc: '', // 维度描述
  list: [] // 关联的一些维度
};
const formData = reactive({
  ...defaultFormData,
  list: [].concat(defaultFormData.list) // todo: 解决引用带来的问题，还有其他的方案吗
});

// 获取数据表
const tableList = ref<any>();
const getTableList = async (query: any) => {
  try {
    const res = await API.dataTable.postDataTableGetTableList(query);
    if (res.data) {
      tableList.value = res.data || [];
    }
  } catch (error) {
    throw error;
  }
};

// 根据表id获取表的对应字段
const tableFieldList = ref<any[]>([]);
const bindDimensionList = ref<any[]>([]);
watch(
  () => store.state.model.bindDimensionList,
  () => {
    bindDimensionList.value = store.state.model.bindDimensionList;
  }
);
// 用来存当前已绑定过的字段名称
watch(
  bindDimensionList,
  (newVal) => {
    // todo: 主键关联
    // if (newVal?.length) {
    tableFieldList.value?.forEach((item: any) => {
      if (
        newVal?.some(
          (subItem: any) =>
            subItem.tableFieldColumn === item.tableFieldName ||
            subItem.tableFieldName === item.tableFieldName
        )
      ) {
        item.relationType = 1;
      } else if (item.relationType === 1) {
        // item.relationType 2 不处理
        item.relationType = 0;
      }
    });
    // }
    if (formData.tableName && newVal.length) {
      formRef.value.clearValidate();
    }
  }
  // {
  //   deep: true
  // }
);
// const updateField = (val: any) => {
//   console.log('此时选中的表');
//   formData.tableId = tableList.value.find((tab: any) => tab.tableName === val)?.id;
//   // formData.tableName = val.tableName;
//   getTableField(formData.tableId);
// };
watch(
  () => formData.tableName,
  () => {
    if (formData.tableName) {
      const id = tableList.value.find(
        (tab: any) => tab.tableName === formData.tableName
      )?.id;
      formData.tableId = id;
      getTableField(id);
      formData.tableId = id;
    }
  }
);

const getTableField = async (query: any) => {
  try {
    const res = await API.dataTable.getDataTableGetTableFieldById({ id: query });
    if (res.data) {
      tableFieldList.value = res.data || [];
      store.commit('model/changeTableList', res.data || []);
      store.commit('model/resetDimensionList');
    }
  } catch (error) {
    throw error;
  }
};

// 点击确定创建
const onBeforeOk = (done: any) => {
  creatDimensionTable()
    .then(() => {
      Message.success('创建成功');
      emit('updateList');
      resetForm();
      done(true);
    })
    .catch((e) => {
      done(false);
    });
};
// 点击绑定
const bindDimension = (item: any) => {
  console.log('进到这了--addDrawer');
  emit('showBindModal', item);
};
// 点击修改(回填维度数据)
const revise = (item: any) => {
  emit('reviseModal', item);
};

const unbind = (record: any) => {
  // 创建处表面处理
  // console.log(record, '此时传来的值');
  let copyDimensionList = bindDimensionList.value.filter(
    (item: any) => item.dimensionName !== record.dimensionName
  );
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '是否确定解绑该维表？',
    content: '维度解绑后，已使用其中维度的场景将无法计算数据，删除后不可恢复',
    simple: false,
    closable: true,
    okText: '确认解绑',
    okButtonProps: {
      style: {
        backgroundColor: '#FF1A3B'
      }
    },
    onBeforeOk: (done) => {
      Message.success('解绑成功');
      store.commit('model/resetDimensionList');
      store.commit('model/changeDimensionList', copyDimensionList);
      done(true);
    }
  });
};

// 确定创建维表
const creatDimensionTable = async () => {
  // @ts-ignore
  formData.list = bindDimensionList.value;
  const err = await formRef.value.validate();
  if (!err) {
    const params = {
      tableId: Number(formData.tableId),
      tableName: formData.tableName,
      dimensionTableDesc: formData.dimensionTableDesc,
      list: formData.list
    };
    try {
      const res = await API.dataTable.postDataTableSetDimTableBind({ ...params });
      if (res.code !== 200) {
        throw new Error('接口错误');
      }
      return true;
    } catch (error) {
      throw error;
    }
  }
  {
    throw new Error('校验错误');
  }
};

// 重置表单的数据
const resetForm = () => {
  formRef.value.clearValidate();
  formRef.value.resetFields();
  tableFieldList.value = [];
  store.commit('model/changeTableList', []);
  store.commit('model/resetDimensionList');
};

// 打开抽屉
const onOpen = () => {
  getTableList({
    pageNum: 1,
    pageSize: 100,
    tableType: 0
  });
};

// todo: 需要解决 Drawer 和 Modal Form 的问题
const onDrawerClose = () => {
  Object.keys(defaultFormData).forEach((key) => {
    formData[key] = defaultFormData[key];
  });
  resetForm();
};
</script>

<template>
  <a-drawer
    unmountOnClose
    :width="684"
    title="创建维表"
    @open="onOpen"
    @before-ok="onBeforeOk"
    @close="
      () => {
        onDrawerClose();
      }
    "
  >
    <a-form
      ref="formRef"
      :model="formData"
      auto-label-width
      style="height: 100%"
    >
      <div class="title">基本信息</div>
      <a-form-item
        show-colon
        required
        label="数据表"
        field="tableName"
        :rules="[{ required: true, message: '请选择数据表' }]"
      >
        <a-select v-model="formData.tableName" placeholder="请选择">
          <a-option
            v-for="item of tableList"
            :value="item.tableName"
            :label="item.tableName"
            :key="item.id"
          />
        </a-select>
      </a-form-item>
      <a-form-item show-colon label="维表描述" field="dimensionTableDesc">
        <a-input v-model="formData.dimensionTableDesc" />
      </a-form-item>
      <div class="title">绑定维度</div>
      <a-form-item
        show-colon
        required
        label="绑定维度"
        field="list"
        :rules="[
          {
            required: true,
            message: '请绑定维度'
          }
        ]"
        class="bind-dimension-item"
      >
      </a-form-item>
      <div class="bind-dimension-content">
        <DimensionModelGraph
          :style="{ flex: 1 }"
          :sourceList="tableFieldList"
          :targetList="bindDimensionList"
          @bindDimension="bindDimension"
          @revise="revise"
          @unbind="unbind"
        />
      </div>
    </a-form>
  </a-drawer>
</template>

<style lang="scss" scoped>
.title {
  color: #33353b;
  font-weight: 600;
}
::v-deep(.bind-dimension-item) {
  .arco-form-item-message {
    position: relative;
    left: -72px;
    top: -8px;
  }
}
.bind-dimension-content {
  display: flex;
  justify-content: space-between;
  margin-top: -10px;
  flex: 1;
  .left-field-name-ul,
  .right-bind-dimension-ul {
    ::v-deep(.arco-list) {
      border: 1px solid rgba(232, 235, 242, 1);
      border-radius: 3px;
      border-top: 3px solid #396efe;
      width: 250px;
      height: 510px;
      overflow-y: auto;
      .arco-list-header {
        font-size: 16px;
        color: #33353b;
        letter-spacing: 0;
        line-height: 22px;
        font-weight: 600;
        padding: 14px;
        border-bottom: 1px solid rgba(232, 235, 242, 1);
      }
      .arco-list-content {
        .arco-list-item {
          padding: 10px 18px;
          box-sizing: border-box;
          font-size: 14px;
          &:hover {
            cursor: pointer;
            background: #f6f8fc;
          }
          .arco-list-item-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            &:hover {
              .field-name {
                max-width: 146px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
              .bind-operate {
                display: block;
              }
            }
            .field-icon {
              width: 16px;
              height: 16px;
              margin-right: 16px;
            }
            .field-name {
              flex: 1;
              .success-icon {
                width: 16px;
                height: 16px;
                margin-left: 5px;
                vertical-align: middle;
              }
            }
            .bind-operate {
              font-size: 14px;
              color: #3c6eff;
              letter-spacing: 0;
              font-weight: 400;
              display: none;
            }
            .no-operate {
              font-size: 12px;
              color: #bbbfcc;
              letter-spacing: 0;
              line-height: 22px;
              font-weight: 400;
            }
          }
        }
      }
      .no-data {
        font-size: 14px;
        color: #9b9fab;
        letter-spacing: 0;
        text-align: center;
        line-height: 22px;
        font-weight: 400;
        text-align: center;
        margin-top: 200px;
      }
    }
  }
}
</style>
